package cn.bdqn.pn.service.order.OrderServiceImpl;

import cn.bdqn.pn.pojo.base.Address;
import cn.bdqn.pn.pojo.commodity.Commodity;
import cn.bdqn.pn.pojo.commodity.Sku;
import cn.bdqn.pn.pojo.order.MainOrder;
import cn.bdqn.pn.pojo.order.MainOrderPackaging;
import cn.bdqn.pn.reposity.base.AddressRepository;
import cn.bdqn.pn.reposity.commodity.CommodityReposity;
import cn.bdqn.pn.reposity.commodity.SkuReposity;
import cn.bdqn.pn.reposity.order.MainOrderReposity;
import cn.bdqn.pn.service.order.MainOrderService;
import cn.bdqn.pn.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("mainOrderService")
public class MainOrderServiceImpl implements MainOrderService {

    @Autowired
    MainOrderReposity mainOrderReposity;
    @Autowired
    CommodityReposity commodityReposity;
    @Autowired
    SkuReposity skuReposity;
    @Autowired
    AddressRepository addressRepository;

    @Override
    public Map<String, Object> selectMainOrderInfoPackaging(MainOrder mainOrder, Integer pageNum, Integer pageSize) {
        Specification<MainOrder> specification = new Specification<MainOrder>() {
            @Override
            public Predicate toPredicate(Root<MainOrder> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (mainOrder.getOrderNum() != null && !mainOrder.getOrderNum().equals("")) {
                    list.add(cb.equal(root.get("orderNum"), mainOrder.getOrderNum()));
                } else {
                    if (mainOrder.getStatus() != null && mainOrder.getStatus() != -1) {
                        list.add(cb.equal(root.get("status"), mainOrder.getStatus()));
                    }
                    if (mainOrder.getOrderTime() != null && !mainOrder.getOrderTime().equals("")
                            && mainOrder.getPayTime() != null && !mainOrder.getPayTime().equals("")) {
                        list.add(cb.between(root.get("orderTime"), mainOrder.getOrderTime(), mainOrder.getPayTime()));
                    } else {
                        if (mainOrder.getOrderTime() != null && !mainOrder.getOrderTime().equals("")) {
                            Date date = new Date();
                            list.add(cb.between(root.get("orderTime"), mainOrder.getOrderTime(), date));
                        }
                        if (mainOrder.getPayTime() != null && !mainOrder.getPayTime().equals("")) {
                            Date date = new Date();
                            list.add(cb.lessThan(root.get("orderTime"), mainOrder.getPayTime()));
                        }
                    }

                }
                if (mainOrder.getMainOrderId() != null) {
                    list.add(cb.equal(root.get("mainOrderId"), mainOrder.getMainOrderId()));
                }
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        };

        Pageable pageable = new PageRequest(pageNum = pageNum == null ? 0 : pageNum, pageSize = pageSize == null ? 2 : pageSize, new Sort(new Sort.Order(Sort.Direction.DESC, "orderTime")));
        Map map = new HashMap();
        Page<MainOrder> orderInfo = mainOrderReposity.findAll(specification, pageable);
        Page<MainOrderPackaging> p = null;//new PageImpl(orderInfo.getContent());
        List<MainOrderPackaging> list = new ArrayList<MainOrderPackaging>();
        List<Address> listAddress=addressRepository.findAll();
        for (int i = 0; i < orderInfo.getContent().size(); i++) {
            MainOrderPackaging packaging = new MainOrderPackaging();
            packaging.setStatus(orderInfo.getContent().get(i).getStatus());
            packaging.setLogisticsNum(orderInfo.getContent().get(i).getLogisticsNum());
            packaging.setAddressId(orderInfo.getContent().get(i).getAddressId());
            packaging.setCount(orderInfo.getContent().get(i).getCount());
            packaging.setDeliverType(orderInfo.getContent().get(i).getDeliverType());
            packaging.setMainOrderId(orderInfo.getContent().get(i).getMainOrderId());
            packaging.setOrderNum(orderInfo.getContent().get(i).getOrderNum());
            packaging.setOrderTime(orderInfo.getContent().get(i).getOrderTime());
            packaging.setPayTime(orderInfo.getContent().get(i).getPayTime());
            packaging.setPostage(orderInfo.getContent().get(i).getPostage());
            packaging.setSkuId(orderInfo.getContent().get(i).getSkuId());
            packaging.setTotalPrice(orderInfo.getContent().get(i).getTotalPrice());
            packaging.setUserId(orderInfo.getContent().get(i).getUserId());


            Integer skuId = orderInfo.getContent().get(i).getSkuId();
            Sku sku = skuReposity.findOne(skuId);
            Integer commodityId = sku.getCommdityId();
            Commodity commodity = commodityReposity.findOne(commodityId);
            packaging.setImgUrl(commodity.getImgURL());
            packaging.setCommodityName(commodity.getCommodityName());
            for(int j=0;j<listAddress.size();j++){
                if(orderInfo.getContent().get(i).getAddressId()==listAddress.get(j).getAddressid()){
                    packaging.setReceiveAddress(listAddress.get(j).getReceiveaddress());
                    packaging.setReceiveName(listAddress.get(j).getReceivename());
                    packaging.setTelephone(listAddress.get(j).getTelephone());
                }
            }
            list.add(packaging);
        }
        p= new PageImpl(list);
        map.put("p", p);
        map.put("orderInfo", orderInfo);
        return map;
    }

    @Override
    public Page<MainOrder> selectMainOrderInfo(MainOrder mainOrder, Integer pageNum, Integer pageSize) {
        Specification<MainOrder> specification = new Specification<MainOrder>() {
            @Override
            public Predicate toPredicate(Root<MainOrder> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (mainOrder.getOrderNum() != null && !mainOrder.getOrderNum().equals("")) {
                    list.add(cb.equal(root.get("orderNum"), mainOrder.getOrderNum()));
                } else {
                    if (mainOrder.getStatus() != null && mainOrder.getStatus() != -1) {
                        list.add(cb.equal(root.get("status"), mainOrder.getStatus()));
                    }
                    if (mainOrder.getOrderTime() != null && !mainOrder.getOrderTime().equals("")
                            && mainOrder.getPayTime() != null && !mainOrder.getPayTime().equals("")) {
                        list.add(cb.between(root.get("orderTime"), mainOrder.getOrderTime(), mainOrder.getPayTime()));
                    } else {
                        if (mainOrder.getOrderTime() != null && !mainOrder.getOrderTime().equals("")) {
                            Date date = new Date();
                            list.add(cb.between(root.get("orderTime"), mainOrder.getOrderTime(), date));
                        }
                        if (mainOrder.getPayTime() != null && !mainOrder.getPayTime().equals("")) {
                            Date date = new Date();
                            list.add(cb.lessThan(root.get("orderTime"), mainOrder.getPayTime()));
                        }
                    }

                }
                if (mainOrder.getMainOrderId() != null) {
                    list.add(cb.equal(root.get("mainOrderId"), mainOrder.getMainOrderId()));
                }
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        };

        Pageable pageable = new PageRequest(pageNum = pageNum == null ? 0 : pageNum, pageSize = pageSize == null ? 2 : pageSize, new Sort(new Sort.Order(Sort.Direction.DESC, "orderTime")));
        return mainOrderReposity.findAll(specification, pageable);
    }


    @Override
    public Integer updMainOrderStatusByMainOrderId(Integer mainOrderId, String logisticsNum) {
        MainOrder mainOrder = mainOrderReposity.findOne(mainOrderId);
        mainOrder.setStatus(2);
        mainOrder.setLogisticsNum(logisticsNum);
        MainOrder mainOrder1 = mainOrderReposity.save(mainOrder);
        if (mainOrder1 != null) {
            return 1;
        }
        return 0;
    }

    @Override
    public Integer addMianOrderLogisticsNum(Integer mainOrderId, String logisticsNum) {
        MainOrder mainOrder = mainOrderReposity.findOne(mainOrderId);
        mainOrder.setLogisticsNum(logisticsNum);
        MainOrder mainOrder1 = mainOrderReposity.save(mainOrder);
        if (mainOrder1 != null) {
            return 1;
        }
        return 0;
    }


    /**
     * 统计近七天每天销售额
     * TimeUtil.zhiqian()为当前时间七天前
     */
    @Override
    public Map<String, Double> getPriceSumByDay() {
        System.out.println("之前时间" + TimeUtil.zhiqian());

        //sql查询出来的集合
        List<MainOrder> list = mainOrderReposity.getTotalPriceByDay(TimeUtil.zhiqian());

        // 近7天每天的总金额   key某天的日期     value 这个日期的总金额
        Map<String, Double> DateSumMoneys = new HashMap<String, Double>();

        for (int i = 0; i < list.size(); i++) {
            MainOrder mainOrder = list.get(i);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");//只把日期转换成字符串不带时间
            String stringDate = dateFormat.format(mainOrder.getPayTime());    //获取日期
            if (DateSumMoneys.get(stringDate) == null) {//判断是否存在这个日期的key 不存在创建一个零销售额的key/value
                DateSumMoneys.put(stringDate, 0.0);
            }
            DateSumMoneys.put(stringDate, DateSumMoneys.get(stringDate) + mainOrder.getTotalPrice());//时间作为key插入key上次的销售额+这个订单的价格
        }
        return DateSumMoneys;
    }


    /**
     * 条件查集合--统计
     */
    @Override
    public List<MainOrder> getZongCount(MainOrder mainOrder) {
        Specification<MainOrder> specification = new Specification<MainOrder>() {
            @Override
            public Predicate toPredicate(Root<MainOrder> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (mainOrder.getStatus() != null && mainOrder.getStatus() != 0) {
                    list.add(cb.equal(root.get("status"), mainOrder.getStatus()));
                }
                Predicate[] predicates = new Predicate[list.size()];
                return cb.and(list.toArray(predicates));
            }
        };
        List<MainOrder> mainOrderList = mainOrderReposity.findAll(specification);
        return mainOrderList;
    }

    /**
     * 根据订单id和状态查
     *
     * @param mainOrder
     * @param status
     * @return
     */
    @Override
    public Integer countByMainOrderIdAndStatus(Integer mainOrder, Integer status) {
        return mainOrderReposity.countByMainOrderIdAndStatus(mainOrder, status);
    }


    /**
     * 商品销售排行
     *
     * @return
     */
    @Override
    public List<MainOrder> selectPaiHang(MainOrder mainOrder) {
        Specification<MainOrder> specification = new Specification<MainOrder>() {
            @Override
            public Predicate toPredicate(Root<MainOrder> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (mainOrder.getOrderNum() != null && !mainOrder.getOrderNum().equals("")) {
                    list.add(cb.equal(root.get("orderNum"), mainOrder.getOrderNum()));
                }
                if (mainOrder.getStatus() != null && mainOrder.getStatus() != -1) {
                    list.add(cb.equal(root.get("status"), mainOrder.getStatus()));
                }
                if (mainOrder.getOrderTime() != null && !mainOrder.getOrderTime().equals("")
                        && mainOrder.getPayTime() != null && !mainOrder.getPayTime().equals("")) {
                    list.add(cb.between(root.get("orderTime"), mainOrder.getOrderTime(), mainOrder.getPayTime()));
                }
                if (mainOrder.getOrderTime() != null && !mainOrder.getOrderTime().equals("")) {
                    Date date = new Date();
                    list.add(cb.between(root.get("orderTime"), mainOrder.getOrderTime(), date));
                }
                if (mainOrder.getPayTime() != null && !mainOrder.getPayTime().equals("")) {
                    Date date = new Date();
                    list.add(cb.lessThan(root.get("orderTime"), mainOrder.getPayTime()));
                }
                if (mainOrder.getMainOrderId() != null) {
                    list.add(cb.equal(root.get("mainOrderId"), mainOrder.getMainOrderId()));
                }
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        };
        return mainOrderReposity.findAll(specification);
    }






}


